layui.use(['util'], function(util){
	  var laypage = util.laypage, //分页
		  layedit = util.layedit, //html编辑器
		  form = util.form, //表单
		  table = util.table; //表格
	      treeSelect = util.treeSelect; //表格

	  var goodsDescriptionIndex;
	  var searchKeyword;
	  var goods = {

		  _constans: {
	          html: {
	              add: appUrl+'/resources/js/lib/goods/goodAdd.html'
	          },
	          api: {
	              add: appUrl + "/goods/addGoods",
	              edit: appUrl + "/goods/editGoods",
	              del: appUrl + "/goods/delGoods",
	              queryGoodsList:appUrl + '/goods/queryGoodsList',
	              uploadImage: appUrl+'/goods/uploadGoodsImage',
	              queryAttrTreeData: appUrl + '/goods/queryAttrTreeData'
	          }
	      },

		  _init : function(){
			  var _this = this;
			  _this.bindEvent();
			  _this._renderTable();
			  _this._tableToolbar();
			  _this._tableTool();
		  },

		  bindEvent: function() {
		      var _this = this;
		      $("#searchButton").on("click", function(event) {
		    	  _this._searchButtonClick();
		      });
		    },

		  _renderTable:function(){
			  var _this = this;
			//执行一个 table 实例
			  table.render({
			    elem: '#goodsTable',
			    url: appUrl+'/goods/queryGoodsList', //数据接口
			    method: 'post', //如果无需自定义HTTP类型，可不加该参数
			    where: {
			    	"goodsName": searchKeyword
			    },
			    title: '商品表',
			    page: true ,//开启分页
			    toolbar: 'default', //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
			    totalRow: false ,//开启合计行
			    cols: [[ //表头
			      {type: 'checkbox', fixed: 'left'},
			      {field: 'name', title: '商品名称', width:200},
			      {field: 'goodsNumber', title: '商品数量', width: 90, sort: true, totalRow: true},
			      {field: 'goodsBrief', title: '商品信息',},
			      {field: 'goodsUnit', title: '商品单位', width: 80, sort: true, totalRow: true},
			      {field: 'retailPrice', title: '零售价', width:150} ,
			      {field: 'sign', title: '签名', width: 200},
			      {field: 'classify', title: '职业', width: 100},
			      {field: 'goodsDesc', title: '商品描述', width: 135, sort: true, totalRow: true},
			      {fixed: 'right', width: 165, align:'center', toolbar: '#goodsTableBar'}
			    ]]
			  });
		  },

		  _tableToolbar : function(){
			  var _this = this;
			//监听头工具栏事件
			  table.on('toolbar(goodsTableBarFilter)', function(obj){
			    var checkStatus = table.checkStatus(obj.config.id),
			    	data = checkStatus.data; //获取选中的数据
			    switch(obj.event){
			      case 'add':
			    	  	_this._addGoods();
			      break;
			      case 'update':
			        if(data.length === 0){
			          layer.msg('请选择一行');
			        } else if(data.length > 1){
			          layer.msg('只能同时编辑一个');
			        } else {
			        	_this._editGoods(data[0]);
			        }
			      break;
			      case 'delete':
			        if(data.length === 0){
			          layer.msg('请选择一行');
			        } else {
			        	var ids = [];
			        	for (var i = 0; i < data.length; i++) {
							ids.push(data[i].id);
						}
			        	layer.confirm('真的删除么', function(index){
			        		_this._deleteGoods(ids.join(","));
			        	});
			        }
			      break;
			    };
			  });
		  },

		  _tableTool : function(){
			  var _this = this;
			//监听行工具事件
			  table.on('tool(goodsTableBarFilter)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
			    var data = obj.data, //获得当前行数据
			    	layEvent = obj.event; //获得 lay-event 对应的值
			    if(layEvent === 'detail'){
			      layer.msg('查看操作');
			    } else if(layEvent === 'del'){
			      layer.confirm('真的删除么', function(index){
			    	  _this._deleteGoods(data.id);
			      });
			    } else if(layEvent === 'edit'){
			    	_this._editGoods(data);
			    }
			  });
		  },

		  _addGoods : function(data){
			    var _this = this;
			    _this._renderLayer("新增商品",_this._constans.api.add);
			    goodsDescriptionIndex = layedit.build("goodsDescription");
		  },

          _renderSelectTree: function (selectedId) {
			  var _this = this;

			  treeSelect.render({
		            // 选择器
		            elem: '#goodsTree',
		            // 数据
		            data: _this._constans.api.queryAttrTreeData,
		            // 异步加载方式：get/post，默认get
		            type: 'post',
		            // 占位符
		            placeholder: '选择商品分类',
		            // 是否开启搜索功能：true/false，默认false
		            search: true,
		            // 点击回调
		            click: function(d){
		            },
		            // 加载完成后的回调函数
		            success: function (d) {
		                if(selectedId){
		                	treeSelect.checkNode('goodsTree', selectedId);
		                }
		            }
		        });
		  },

		  _editGoods : function(data){
			  var _this = this;
			    _this._renderLayer("编辑商品",_this._constans.api.edit,data);
			    form.val("goodsForm", {
		    	  "goodsBrief": data.goodsBrief,
		    	  "goodsDesc": data.goodsDesc,
		    	  "goodsNumber": data.goodsNumber,
		    	  "goodsUnit":data.goodsUnit,
                    "isNew": data.isNew,
                    "isHot": data.isHot,
		    	  "id": data.id,
		    	  "name": data.name,
                    "retailPrice": data.retailPrice
		    	});
			    goodsDescriptionIndex = layedit.build("goodsDescription");
		  },

          _renderLayer: function (title, url, data) {
			  var _this = this;
			  var goodHtml = util.getTemPlates(_this._constans.html.add);
			  layer.open({
				  type: 1,
				  title:title,
				  shade: 0,
				  area: ['1000px','800px'],
				  content: goodHtml,
				  btn:['确定','取消'],
				  btnAlign: 'c',
				  yes: function (index, e) {
					  form.verify();
					  var formData = util.getFormData($(e).find('form'));
					  var goodsDescription =layedit.getContent(goodsDescriptionIndex);
					  var treeObj = treeSelect.zTree('goodsTree');
					  var checkNodes = treeObj.getSelectedNodes(true);
					  if(checkNodes.length && checkNodes.length > 0){
						  formData.categoryId = checkNodes[0].id;
					  }
					  formData.goodsDesc = goodsDescription;
                      formData.isHot = formData.isHot === 'on';
                      formData.isNew = formData.isNew === 'on';
					  util.post(url,formData,function (resp) {
                          if (resp && resp.success) {
                              layer.closeAll();
                              _this._init();
                          }
                      });
                  },
                  btn2: function(index, layero){
                	  layer.closeAll();
            	  },
                  cancel: function () {
                      layer.closeAll();
                  }
				});
			  form.render();
			  if(data){
				  _this._renderSelectTree(data.categoryId);
			  }else{
				  _this._renderSelectTree();
			  }
			  layedit.set({//设置图片的传输地址
		    	  uploadImage: {
		    	    url: _this._constans.api.uploadImage , //接口url
		    	    type: 'post' //默认post
		       }
		      });
		  },

		  _deleteGoods : function (ids){
			  var _this = this;
			  util.post(_this._constans.api.del, {id: ids}, function (resp) {
				  if(resp.result){
					  layer.msg('删除成功');
				  }else{
					  layer.msg('删除失败');
				  }
	              layer.closeAll();
	              _this._init();
	            });
		  },

          _searchButtonClick: function () {
			  var _this = this;
			  var keyword = $("#searchGoodsName").val();
			  if(!keyword.trim()){
				  layer.msg('请输入查询内容');
				  return;
			  }
			  searchKeyword = keyword;
			  _this._init();
		  }

  		};
	  goods._init();

});